package org.wangchaocheng.cloudgallery.i18n;

import java.util.Locale;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.wangchaocheng.cloudgallery.common.utils.SpringContextHolder;

/**
 * 国际化工具类
 *
 * @author wangchaocheng
 * @date 2025/04/23
 */
@Slf4j
public class I18nFactory {

    private static final I18nConfig localeResolver = SpringContextHolder.getBean("i18nConfig");

    /**
     * 获取国际化后内容信息
     *
     * @param code 国际化key
     * @return 国际化后内容信息
     */
    public static String getMessage(String code) {
        Locale locale = localeResolver.resolveLocale();
        return getMessage(code, null, code, locale);
    }

    /**
     * 获取指定语言中的国际化信息，如果没有则走英文
     *
     * @param code 国际化 key
     * @param lang 语言参数
     * @return 国际化后内容信息
     */
    public static String getMessage(String code, String lang) {
        Locale locale;
        if (StringUtils.isEmpty(lang)) {
            locale = Locale.US;
        } else {
            try {
                var split = lang.split("-");
                locale = new Locale(split[0], split[1]);
            } catch (Exception e) {
                locale = Locale.US;
            }
        }
        return getMessage(code, null, code, locale);
    }

    public static String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setDefaultEncoding(localeResolver.getMessageEncoding());
        messageSource.setBasename(localeResolver.getMessageBasename());
        String content;
        try {
            content = messageSource.getMessage(code, args, locale);
        } catch (Exception e) {
            log.error("I18nUtil===[获取国际化参数失败]{}", ExceptionUtils.getStackTrace(e));
            content = defaultMessage;
        }
        return content;
    }
}
